define(['jquery', 'select2','datetimepicker',"controller","rights","moment","validate"], function ($) {

    var c = require("controller");
    var rights = require("rights");
    var moment = require("moment");
    var tHeight = $(window).height() - 50 - 35;
    $(".content").height(tHeight);

    var Companys=c.getAllCompanys();
    return {
        init: function () {
            // test set token
            // localStorage.setItem('token', 'MiMxNDcyNjk0Mjk4QGcuZmx5LWNsb3VkLmNuI1pjZDYzQ2tqeXg1MzdHSkRQWU43SEkxUS9Ecz0=');
            $("#searchCompanys").select2({
                data:c.formatCompanysToSelect(Companys)
            });
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow:null,
        searchData:{},
        initDataTable: function () {
            var self = this;
            this.dataTable = c.myDataTable($("#mmg"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length
                    };
                    $.extend(true,param,self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "device/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.devices;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (tHeight - 270) + "px",
                scrollCollapse: true,
                columns: [
                    {"data": "did"},
                    {"data": "factory_time"},
                    {"data": "cid"},
                    {"data": "model"},
                    {"data": "oem"}
                ],
                columnDefs: [
                    {
                        "targets": 1,//
                        "data": "factory_time",
                        "render": function (data, type, row) {
                            return moment(row.factory_time,'X').format('YYYY-MM-DD');//c.formatDateWithoutSFromInt(row.factory_time);
                        }
                    },
                    {
                        "targets": 2,//所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 5,//操作按钮目标列
                        "data": null,
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" +
                                "<a href='#' class='btn btn-sm btn-info edit' data-toggle='modal' data-target='#myModal' data-rights='7004'><i class='fa fa-edit'></i>编辑</a>" +
                                "<a href='#' class='btn btn-sm btn-danger' data-rights='7005'><i class='fa fa-remove'></i>删除</a>" +
                                "</div>";
                            return html;
                        }
                    }],
                drawCallback: function(settings, json) {
                    rights.isShowFn($('.content'));
                }
            });
        },
        bindEvent: function () {
            var self = this;
            $('#add').on('click', function () {
                //添加
                $("#myModal>.modal-dialog").load("device/form.html", function(){
                    self.formInit()
                });
            });
            $('#mmg').on('click', '.edit', function () {
                    //编辑
                    var dataRow = self.dataTable.row( $(this).parents('tr') ).data();
                    $("#myModal>.modal-dialog").load("device/form.html", function(){
                        self.formInit(dataRow)
                    });  
                })
                .on('click', '.btn-danger', function () {
                    //删除
                    self.delRow= $(this).parents('tr')
                    var dataRow = self.dataTable.row(self.delRow).data();
                    c.confirm({
                        content: "是否删除",
                        confirm: function () {
                            c.ajax({
                                    url: "device/delete",
                                    data: {
                                        cid: dataRow.cid,
                                        did: dataRow.did
                                    },
                                    success: function (res) {
                                        if (res.err < 0) {
                                            alert(res.msg);
                                            return
                                        }
                                        self.dataTable.ajax.reload();
                                    }
                                }
                            )
                        }
                    })
                })
                .on('click', 'tr', function () {
                    $(this).siblings().removeClass("select");
                    $(this).toggleClass("select");

                });
            $('#search').on('click',function () {
                self.searchData={
                    // did:$('#searchDid').val(),
                    // model:$('#searchModel').val(),
                    // oem:$('#searchOem').val()
                };
                var cid = $('#searchCompanys').val();
                var did = $('#searchDid').val();
                var model = $('#searchModel').val();
                var oem = $('#searchOem').val();
                if(did!=''){
                    self.searchData.did = did
                } if(model!=''){
                    self.searchData.model = model
                }if(oem!=''){
                    self.searchData.oem = oem
                }
                if(cid!=''){
                    self.searchData.cid = cid
                }
                self.dataTable.draw();
            });

            $('[name="role"]').on('change', function () {
                if ($('[name="role"]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
            });

            $('.search-input').on('keyup', function () {
                console.log(this.value);
                // self.dataTable.search(this.value, false, false).draw();
            })

        },
        formInit:function (dataRow) {
            var self=this;
            var $form = $('.edit-form');
            //获取公司

            $("#companys").select2({
                data:c.formatCompanysToSelect(Companys)
            });
            //本地时间
            var newDate = new Date();
            var t       = newDate.toJSON();
            $("#factory_time").datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD'
            });

            if(dataRow){//判断是否编辑
                var fTime = c.formatYMDFromInt(dataRow.factory_time);
                $form.children("#did").hide();
                $form.find('[name="factory_time"]').val(fTime);
                $form.find('[name="model"]').val(dataRow.model);
                $form.find('[name="oem"]').val(dataRow.oem);
                $form.find('[name="cid"]').val(dataRow.cid).trigger("change");
                $form.find('[name="did"]').val(dataRow.did);
                $('#myModal').find('.modal-title').text('编辑设备');
                var cid = dataRow.cid;
            }

            $('.edit-form').validate({
                rules:{
                    did:{
                        isAscii:true
                    },
                    model:{
                        isAscii:true
                    }
                },
                submitHandler: function (form) {
                    var mode = $('#myModal').find('.modal-title').text();
                    var formData = new FormData($('.edit-form').get(0));
                    // 时间回转
                    var fdata =  Date.parse(formData.get('factory_time')) / 1000;
                    var params = {
                        cid: formData.get('cid'),
                        did: formData.get('did'),
                        oem: formData.get('oem'),
                        factory_time: formData.get('factory_time'),
                        model: formData.get('model')
                    };

                    if(params.factory_time==""){
                        c.alert({
                            content:'请选择出厂时间'
                        });
                        return false;
                    }else{
                        params.factory_time =  Date.parse(formData.get('factory_time')) / 1000;
                    }

                    if (params.role === 'CORP') {
                        params['cid'] = formData.get('cid')
                    }
                    var url='device/';
                    if (mode === "添加设备") {
                        url+= 'create';
                    } else {
                        url+= 'update';
                        params.cid = cid
                        params.cid2 = formData.get('cid')
                    }
                    c.ajax({
                        url: url,
                        dataType: "json",
                        cache: false,
                        data: params,
                        success: function (res) {
                            $('#myModal').modal('hide')
                            if (res.err < 0) {
                                return;
                            }
                            self.dataTable.ajax.reload();
                        }
                    });

                }
            });

        }
    }
});



